{% extends 'base.html' %}
{% load static %}

{% block title %}注册 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .register-container {
        min-height: calc(100vh - 200px);
        padding: 3rem 0;
    }
    
    .register-card {
        background: white;
        border-radius: 1.5rem;
        box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        padding: 3rem;
        max-width: 600px;
        margin: 0 auto;
    }
    
    .step-indicator {
        display: flex;
        justify-content: space-between;
        margin-bottom: 2rem;
        position: relative;
    }
    
    .step-indicator::before {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        right: 0;
        height: 2px;
        background: #e2e8f0;
        z-index: 0;
    }
    
    .step {
        flex: 1;
        text-align: center;
        position: relative;
        z-index: 1;
    }
    
    .step-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #e2e8f0;
        color: #718096;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-bottom: 0.5rem;
        transition: all 0.3s ease;
    }
    
    .step.active .step-circle {
        background: var(--gradient-primary);
        color: white;
    }
    
    .step.completed .step-circle {
        background: var(--success-color);
        color: white;
    }
    
    .form-step {
        display: none;
    }
    
    .form-step.active {
        display: block;
        animation: fadeIn 0.5s ease;
    }
    
    .password-strength {
        margin-top: 0.5rem;
    }
    
    .strength-bar {
        height: 4px;
        background: #e2e8f0;
        border-radius: 2px;
        overflow: hidden;
    }
    
    .strength-bar-fill {
        height: 100%;
        transition: all 0.3s ease;
        width: 0;
    }
</style>
{% endblock %}

{% block content %}
<div class="register-container">
    <div class="container">
        <div class="register-card">
            <h2 class="text-center mb-4">
                <i class="fas fa-user-plus text-primary"></i> 注册新账号
            </h2>
            
            <!-- 步骤指示器 -->
            <div class="step-indicator">
                <div class="step active" data-step="1">
                    <div class="step-circle">1</div>
                    <div class="step-label">基本信息</div>
                </div>
                <div class="step" data-step="2">
                    <div class="step-circle">2</div>
                    <div class="step-label">账号设置</div>
                </div>
                <div class="step" data-step="3">
                    <div class="step-circle">3</div>
                    <div class="step-label">完善资料</div>
                </div>
            </div>
            
            <form id="registerForm">
                {% csrf_token %}
                
                <!-- 步骤1：邮箱验证 -->
                <div class="form-step active" data-step="1">
                    <div class="mb-3">
                        <label for="email" class="form-label-custom">
                            <i class="fas fa-envelope me-1"></i> QQ邮箱 <span class="text-danger">*</span>
                        </label>
                        <div class="input-group">
                            <input type="email" class="form-control form-control-custom" id="email" name="email" placeholder="请输入QQ邮箱" required>
                            <button class="btn btn-outline-primary" type="button" id="sendCodeBtn">发送验证码</button>
                        </div>
                        <small class="text-muted">支持QQ邮箱、163邮箱等</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="code" class="form-label-custom">
                            <i class="fas fa-key me-1"></i> 邮箱验证码 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-custom" id="code" name="code" placeholder="请输入6位验证码" required maxlength="6">
                        <small class="text-muted">验证码已发送到您的邮箱，请注意查收</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label-custom">
                            <i class="fas fa-mobile-alt me-1"></i> 手机号（可选）
                        </label>
                        <input type="tel" class="form-control form-control-custom" id="phone" name="phone" placeholder="请输入手机号" pattern="[0-9]{11}">
                    </div>
                    
                    <button type="button" class="btn btn-gradient-primary w-100" onclick="nextStep(2)">
                        下一步 <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
                
                <!-- 步骤2：账号设置 -->
                <div class="form-step" data-step="2">
                    <div class="mb-3">
                        <label for="username" class="form-label-custom">
                            <i class="fas fa-user me-1"></i> 用户名 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-custom" id="username" name="username" placeholder="请输入用户名（4-20个字符）" required minlength="4" maxlength="20">
                        <small class="text-muted">用户名将用于登录，仅支持字母、数字和下划线</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password1" class="form-label-custom">
                            <i class="fas fa-lock me-1"></i> 密码 <span class="text-danger">*</span>
                        </label>
                        <input type="password" class="form-control form-control-custom" id="password1" name="password1" placeholder="请输入密码（至少6位）" required minlength="6">
                        <div class="password-strength">
                            <div class="strength-bar">
                                <div class="strength-bar-fill" id="strengthBar"></div>
                            </div>
                            <small id="strengthText" class="text-muted">密码强度：弱</small>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password2" class="form-label-custom">
                            <i class="fas fa-lock me-1"></i> 确认密码 <span class="text-danger">*</span>
                        </label>
                        <input type="password" class="form-control form-control-custom" id="password2" name="password2" placeholder="请再次输入密码" required minlength="6">
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="prevStep(1)">
                            <i class="fas fa-arrow-left me-1"></i> 上一步
                        </button>
                        <button type="button" class="btn btn-gradient-primary" onclick="nextStep(3)">
                            下一步 <i class="fas fa-arrow-right ms-1"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 步骤3：完善资料 -->
                <div class="form-step" data-step="3">
                    <div class="mb-3">
                        <label for="nickname" class="form-label-custom">
                            <i class="fas fa-id-card me-1"></i> 昵称 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-custom" id="nickname" name="nickname" placeholder="请输入昵称" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="interests" class="form-label-custom">
                            <i class="fas fa-heart me-1"></i> 兴趣爱好
                        </label>
                        <div id="interestTags" class="mb-2"></div>
                        <input type="text" class="form-control form-control-custom" id="interestInput" placeholder="输入兴趣标签后按回车添加">
                        <input type="hidden" id="interests" name="interests">
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="agreement" required>
                        <label class="form-check-label" for="agreement">
                            我已阅读并同意 <a href="/terms/" target="_blank">用户协议</a> 和 <a href="/privacy/" target="_blank">隐私政策</a>
                        </label>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="prevStep(2)">
                            <i class="fas fa-arrow-left me-1"></i> 上一步
                        </button>
                        <button type="submit" class="btn btn-gradient-success">
                            <i class="fas fa-check me-1"></i> 完成注册
                        </button>
                    </div>
                </div>
            </form>
            
            <div class="text-center mt-4">
                已有账号？<a href="{% url 'users:login' %}" class="text-decoration-none">立即登录</a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentStep = 1;
    let selectedInterests = [];
    let countdown = 0;
    
    // 步骤切换
    function nextStep(step) {
        if (validateStep(currentStep)) {
            currentStep = step;
            updateSteps();
        }
    }
    
    function prevStep(step) {
        currentStep = step;
        updateSteps();
    }
    
    function updateSteps() {
        // 更新步骤指示器
        document.querySelectorAll('.step').forEach(step => {
            const stepNum = parseInt(step.dataset.step);
            step.classList.remove('active', 'completed');
            if (stepNum === currentStep) {
                step.classList.add('active');
            } else if (stepNum < currentStep) {
                step.classList.add('completed');
            }
        });
        
        // 更新表单步骤
        document.querySelectorAll('.form-step').forEach(step => {
            step.classList.remove('active');
        });
        document.querySelector(`.form-step[data-step="${currentStep}"]`).classList.add('active');
    }
    
    // 验证当前步骤
    function validateStep(step) {
        const stepElement = document.querySelector(`.form-step[data-step="${step}"]`);
        const inputs = stepElement.querySelectorAll('input[required]');
        
        for (let input of inputs) {
            if (!input.checkValidity()) {
                input.reportValidity();
                return false;
            }
        }
        
        if (step === 2) {
            const pwd1 = document.getElementById('password1').value;
            const pwd2 = document.getElementById('password2').value;
            if (pwd1 !== pwd2) {
                showError('两次输入的密码不一致');
                return false;
            }
        }
        
        return true;
    }
    
    // 发送邮箱验证码
    document.getElementById('sendCodeBtn').addEventListener('click', function() {
        const email = document.getElementById('email').value;
        
        // 验证邮箱格式
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailRegex.test(email)) {
            showError('请输入正确的邮箱地址');
            return;
        }
        
        if (countdown > 0) {
            return;
        }
        
        // 发送验证码请求
        API.users.sendCode({ email })
            .then(response => {
                if (response.data.code === 200) {
                    showSuccess('验证码已发送到您的邮箱，请查收！');
                    // 开发环境下，如果返回了验证码，自动填充
                    if (response.data.data && response.data.data.code) {
                        console.log('邮箱验证码：', response.data.data.code);
                        document.getElementById('code').value = response.data.data.code;
                        showSuccess('开发环境：验证码已自动填充');
                    }
                    startCountdown();
                } else {
                    showError(response.data.message || '发送失败');
                }
            })
            .catch(error => {
                showError(error.response?.data?.message || '发送失败，请稍后重试');
            });
    });
    
    function startCountdown() {
        countdown = 60;
        const btn = document.getElementById('sendCodeBtn');
        const interval = setInterval(() => {
            countdown--;
            btn.textContent = `${countdown}秒后重发`;
            btn.disabled = true;
            
            if (countdown === 0) {
                clearInterval(interval);
                btn.textContent = '发送验证码';
                btn.disabled = false;
            }
        }, 1000);
    }
    
    // 密码强度检测
    document.getElementById('password1').addEventListener('input', function() {
        const password = this.value;
        let strength = 0;
        
        if (password.length >= 6) strength++;
        if (password.length >= 10) strength++;
        if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
        if (/\d/.test(password)) strength++;
        if (/[^a-zA-Z0-9]/.test(password)) strength++;
        
        const strengthBar = document.getElementById('strengthBar');
        const strengthText = document.getElementById('strengthText');
        
        if (strength <= 1) {
            strengthBar.style.width = '25%';
            strengthBar.style.background = '#f56565';
            strengthText.textContent = '密码强度：弱';
            strengthText.className = 'text-danger';
        } else if (strength <= 3) {
            strengthBar.style.width = '50%';
            strengthBar.style.background = '#ed8936';
            strengthText.textContent = '密码强度：中';
            strengthText.className = 'text-warning';
        } else {
            strengthBar.style.width = '100%';
            strengthBar.style.background = '#48bb78';
            strengthText.textContent = '密码强度：强';
            strengthText.className = 'text-success';
        }
    });
    
    // 兴趣标签添加
    document.getElementById('interestInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const interest = this.value.trim();
            if (interest && !selectedInterests.includes(interest)) {
                selectedInterests.push(interest);
                updateInterestTags();
                this.value = '';
            }
        }
    });
    
    function updateInterestTags() {
        const container = document.getElementById('interestTags');
        container.innerHTML = selectedInterests.map(interest => `
            <span class="tag-custom">
                ${interest}
                <i class="fas fa-times ms-1" onclick="removeInterest('${interest}')" style="cursor: pointer;"></i>
            </span>
        `).join('');
        
        document.getElementById('interests').value = selectedInterests.join(',');
    }
    
    function removeInterest(interest) {
        selectedInterests = selectedInterests.filter(i => i !== interest);
        updateInterestTags();
    }
    
    // 表单提交
    document.getElementById('registerForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        
        API.users.register(data)
            .then(response => {
                showSuccess('注册成功！即将跳转到登录页面...');
                setTimeout(() => {
                    window.location.href = '{% url "users:login" %}';
                }, 2000);
            })
            .catch(error => {
                showError(error.response?.data?.message || '注册失败，请重试');
            });
    });
</script>
{% endblock %}
